/* eslint-disable no-case-declarations */
/* eslint-disable no-else-return */
import { AnyAction } from 'redux';

import { Lesson } from "@/typings/lesson";
import { ADD_CART_ITEM, REMOVE_CART_ITEM, CLEAR_CART_ITEMS, CHANGE_CART_ITEM_COUNT, CHANGE_CHECKED_CART_ITEMS, SETTLE } from '../action-types';

export interface CartItem {
    lesson: Lesson;
    count: number;
    checked: boolean;
}

export type CartState = CartItem[];

const initialState: CartState = [];
export default function (state: CartState = initialState, action: AnyAction) {
    switch (action.type) {
        case ADD_CART_ITEM:
            {
                const index:number = state.findIndex((item) => item.lesson.id === action.payload.id);
                if (index === -1) {
                    const item: CartItem = {
                        checked: false,
                        count: 1,
                        lesson: action.paylaod as Lesson,
                    };
                    return {
                        ...state,
                        item
                    };
                } else {
                    const list = state.map((item, i:number) => (i === index ? { ...item, count: item.count + 1 } : item));
                    return list;
                }
            }
        case REMOVE_CART_ITEM:
            {
                const list = state.filter((item) => item.lesson.id !== action.payload);
                return list;
            }
        case CLEAR_CART_ITEMS:
            return [];
        case CHANGE_CART_ITEM_COUNT:
            {
                const list = state.map((item) => (item.lesson.id === action.payload.id ? { ...item, count: action.paylaod.count } : item));
                return list;
            }
        case CHANGE_CHECKED_CART_ITEMS:
            const checkedIds = action.payload;
            return state.map((item) => (checkedIds.includes(item.lesson.id) ? { ...item, checked: true } : { ...item, checked: false }));
        case SETTLE:
            return state.filter((item) => !item.checked);
        default:
            return {
                ...state
            };
    }
}
